package com.aivin.lib_englishlearn.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;

import com.aivin.lib_base.tool.MyDeviceInforHelper;
import com.aivin.lib_base.tool.RouteUtils;
import com.aivin.lib_base.tool.WkLog;
import com.aivin.lib_englishlearn.FanyiV3Demo;
import com.aivin.lib_englishlearn.R;
import com.aivin.lib_englishlearn.SelectWordTextView;
import com.aivin.lib_englishlearn.TranslationResult;
import com.aivin.lib_englishlearn.TranslationResultWindow;
import com.aivin.lib_media.myMp3Player.WordReadTool;
import com.aivin.lib_media.myMp3Player.Mp3PlayerTool;
import com.aivin.lib_media.myMp3Player.PlaybackInfoListener;
import com.aivin.lib_media.myMp3Player.PlayerStatus;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.fastjson.JSON;
import com.gyf.immersionbar.ImmersionBar;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;
import java.io.File;
import java.util.List;
import java.util.Locale;

@Route(path = RouteUtils.EnglishLearningActivity)
public class EnglishLearningActivity extends Activity  {
    private SelectWordTextView lrcView ;
    private TextView statusInfo;
    private Activity activity ;
    private Mp3PlayerTool mp3PlayerTool ;
    private WordReadTool wordReadTool ;
    private ImageView playState ;
    private SeekBar seek_bar ;
    private View rootView ;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.englishlearning_layout);
        activity= this ;
        ImmersionBar.with(this)
                .fitsSystemWindows(true)  //使用该属性,必须指定状态栏颜色
                .statusBarColor( R.color.color_333242)
                .init();

        initView();
        initConfig();

        wordReadTool = new WordReadTool() ;
    }


    private void initConfig(){
        Intent intent =getIntent() ;
        String articleContent = intent.getStringExtra("articleContent") ;
        String mediaUrl = intent.getStringExtra("mediaUrl") ;
        String objectId = intent.getStringExtra("objectId") ;

        lrcView.setText(articleContent);

        if("noMedia".equalsIgnoreCase(mediaUrl)){
            findViewById(R.id.controlLay).setVisibility(View.GONE);
        }else{
            String destPath = MyDeviceInforHelper.getEnglishDir()+objectId+".mp3";
            File file =new File(destPath) ;
            if(!file.exists()){
                downFile(mediaUrl ,file.getAbsolutePath());
            }else{
                createPlayer(file.getAbsolutePath()) ;
            }
        }
    }

    private void createPlayer(String destPath){
        if(mp3PlayerTool==null){
            mp3PlayerTool = new Mp3PlayerTool(destPath ,playbackInfoListener) ;
        }
    }

    private void initView(){
        rootView =findViewById(R.id.rootView) ;
        statusInfo =findViewById(R.id.statusInfo) ;
        lrcView =findViewById(R.id.lrcView) ;
        playState =findViewById(R.id.playState) ;
        playState.setOnClickListener(onClickListener);
        seek_bar = findViewById(R.id.seek_bar) ;
        seek_bar.setMax(100);
        seek_bar.setOnSeekBarChangeListener(onSeekBarChangeListener );

        lrcView.setOnClickWordListener(new SelectWordTextView.OnClickWordListener() {
            @Override
            public void onClickWord(String word) {
                WkLog.showLog("选中...."+word );
                if(wordReadTool!=null &&  !TextUtils.isEmpty(word)){
                    wordReadTool.readThWord("http://dict.youdao.com/dictvoice?audio="+word);
                }
                fanyiRequest( word) ;


            }
        });
    }


    private void fanyiRequest(String word  ) {
        x.http().post( FanyiV3Demo.getInstance().getParams(word ), new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                showWindow(result) ;
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                WkLog.showLog("翻译 onError...."+ex.getMessage() );
            }

            @Override
            public void onCancelled(CancelledException cex) {
                WkLog.showLog("翻译 onCancelled...." );
            }

            @Override
            public void onFinished() {
                WkLog.showLog("翻译 onFinished...." );
            }
        });

    }



    private void showWindow(String result){
        WkLog.showLog("翻译返回成功="+ result);
        TranslationResult item = JSON.parseObject(result, TranslationResult.class);

        if(item ==null){
            WkLog.showLog("item=== null="+ result);
            return;
        }

        WkLog.showLog("item=== "+item.toString());
        TranslationResult.BasicBean basicBean = item.getBasic();

        if(basicBean ==null){
            WkLog.showLog("basicBean== null" );
            return;
        }

        List<String> explains = basicBean.getExplains();
        StringBuilder stringBuilder = new StringBuilder() ;
        for(String str : explains){
            stringBuilder.append(str).append("\r\n");
        }
        stringBuilder.append("英音标: ").append(basicBean.getUsphonetic()).append("\r\n");
        stringBuilder.append("美音标: ").append(basicBean.getUkphonetic()) ;
        showTransWindow(stringBuilder.toString()) ;
    }

    private TranslationResultWindow translationResultWindow ;

    private void showTransWindow(String msg){
        if (translationResultWindow == null) {
            translationResultWindow = new TranslationResultWindow(this );
        }
        translationResultWindow.updateMsg(msg);
        translationResultWindow.showAtLocation(rootView, Gravity.TOP , 0, 0);
    }

    private void downFile(String url , String filePath){
        if(TextUtils.isEmpty(url) || TextUtils.isEmpty(filePath) ){
            return;
        }

        WkLog.showLog("下载 url="+url);
        WkLog.showLog("下载 filePath="+filePath);
        RequestParams requestParams = new RequestParams();
        requestParams.setSaveFilePath(filePath);
        requestParams.setUri(url);
        x.http().get( requestParams, new Callback.ProgressCallback<File>() {

            @Override
            public void onSuccess(File result) {
                WkLog.showLog("下载成功"+ result.getAbsolutePath() +"  "+ result.exists());
                statusInfo.setText("下载成功");
                createPlayer(result.getAbsolutePath());
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                WkLog.showLog("下载失败");
                statusInfo.setText("下载失败");
            }

            @Override
            public void onCancelled(CancelledException cex) {
            }

            @Override
            public void onFinished() {
                WkLog.showLog("下载onFinished");
            }

            @Override
            public void onWaiting() {
                WkLog.showLog("下载等待");
                statusInfo.setText("下载等待");
            }

            @Override
            public void onStarted() {
                WkLog.showLog("开始下载");
                statusInfo.setText("开始下载");
            }

            @Override
            public void onLoading(long total, long current, boolean isDownloading) {
                float percent = 100f* current /  total  ;
                WkLog.showLog(" 下载 onLoading "+percent);
                statusInfo.setText("下载:"+(int)percent+"%");

            }
        });
    }




    private PlaybackInfoListener playbackInfoListener = new PlaybackInfoListener() {

        @Override
        public void onPositionChanged(int position,int duration ,boolean isFirst) {
            if(seek_bar!=null){
                int progress =  duration > 0 ?  position * 100 / duration : 0;

                if(!isFirst){
                    activity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            seek_bar.setProgress(progress);
                            statusInfo.setText(String.format(Locale.getDefault(),"%d%%",progress));
                        }
                    });
                }else{
                    statusInfo.setText("准备就绪");
                }
            }
        }

        @Override
        public void onStateChanged(int state) {
            WkLog.showLog("状态改变=="+ state);
            if(playState==null){
                return;
            }

            if(state == PlayerStatus.STATUS_LODING){
                playState.setImageResource(R.mipmap.icon_loading);
            }

            else  if(state == PlayerStatus.STATUS_PREPARED){
                playState.setImageResource(R.drawable.play_selector);
            }

            else  if(state == PlayerStatus.STATUS_PLAYING){
                playState.setImageResource(R.drawable.pause_selector);
            }

            else if(state == PlayerStatus.STATUS_PAUSE){
                playState.setImageResource(R.drawable.play_selector );
            }
        }

        @Override
        public void onPlaybackCompleted() {
            playState.setImageResource(R.drawable.play_selector );
        }
    };


    private View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if(mp3PlayerTool==null){
                return;
            }
            int viewId = view.getId();
            if(R.id.playState == viewId){
                boolean isPlaying =mp3PlayerTool.isPlaying() ;
                if(isPlaying){
                    mp3PlayerTool.pause();
                }else{
                    mp3PlayerTool.play();

                }
            }
        }
    };

    private SeekBar.OnSeekBarChangeListener onSeekBarChangeListener = new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int i, boolean fromUser) {
            if(fromUser && mp3PlayerTool!=null){
                mp3PlayerTool.seekToByPercent( seek_bar.getProgress() );
            }

        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {

        }
    } ;

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(mp3PlayerTool!=null){
            mp3PlayerTool.release();
        }

        if(wordReadTool!=null){
            wordReadTool.release();
        }
    }




}
